﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SubVersionOne
{
    public static class EventLogger
    {
        private static object synch = new object();
        private static string _path;
        public  static void Init() 
           
        {
            _path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SubVersionOne");
            if (Directory.Exists(_path) == false)
            {
                Directory.CreateDirectory(_path);
            }

            _path = Path.Combine(_path, Constants.LogName);
            if (!File.Exists(_path))
            {
                File.Create(_path).Close();
            }
            

        }
        public static void Error(Exception ex)
        {

            Write(String.Format("{0}\n{1}", ex.Message, ex.StackTrace));

            // EventLog.WriteEvent(("SubVersionOne", message, EventLogEntryType.Information,)
            //EventLog.WriteEntry("SubVersionOne", message, EventLogEntryType.Information);

        }
        public static void Info(string message, params object[] parameters)
        {
            string m = message;
            if (parameters != null && parameters.Any())
            {
                m = String.Format(message, parameters);
            }
#if DEBUG
            Write(m);
#endif
    
            
            // EventLog.WriteEvent(("SubVersionOne", message, EventLogEntryType.Information,)
            //EventLog.WriteEntry("SubVersionOne", message, EventLogEntryType.Information);

        }

        private static void Write(string message)
        {
            
            FileInfo fi = new FileInfo(_path);
            bool append = false;
            if (fi.Exists && fi.Length < 536870912)
                append = true;
            else
            {
                append = false;
            }

            lock (synch)
            {
                using (StreamWriter sw = new StreamWriter(fi.FullName, append))
                {
                    sw.WriteLine(message);
                    sw.Flush();
                    sw.Close();
                }
            }
        }
    }
}
